<template>
  <div class="professional-category">
    <div class="left-column">
      <div
        :class="
          firstCategoryIndex == index
            ? 'first-category-active'
            : 'first-category'
        "
        v-for="(firstItem, index) in majorList"
        :key="index"
        @click="changeFirstCategory(index)"
      >
        {{ firstItem.name }}
      </div>
    </div>
    <div
      class="right-column"
      ref="rightContainer"
      @scroll="handleIndustryScroll"
    >
      <div
        class="category"
        v-for="(firstItem, index) in majorList"
        :key="index"
      >
        <div class="first-title">
          <div>{{ firstItem.name }}</div>
        </div>
        <div
          class="second-item"
          v-for="(secondItem, secondIndex) in firstItem.children"
          :key="secondIndex"
          @click="onToggleSecondIndustry(secondItem)"
        >
          <div
            :class="[
              'second-item-title',
              secondItem.showChildren ? 'float-title' : ''
            ]"
          >
            <img
              :class="[
                'arrow-icon',
                secondItem.showChildren ? 'arrow-rotate' : ''
              ]"
              src="@/assets/images/arrow_down.png"
              class="arrow-icon"
              alt=""
            />
            <span class="second-item-title-text">
              <span class="text-content">{{ secondItem.name }}</span>
              <text v-if="secondItem.children" class="count-text"
                >({{ secondItem.children.length || 0 }}个)</text
              >
            </span>
            <img
              @click.stop="onSelectSecondeMajor(secondItem)"
              :src="secondItem.checked ? check : uncheck"
              class="selected-img"
              alt=""
            />
          </div>
          <transition name="slide-fade">
            <div v-if="secondItem.showChildren" class="third-category-wrapper">
              <div
                class="third-item"
                v-for="(_item, _index) in secondItem.children"
                :key="_index"
              >
                <div>{{ _item.name }}</div>
                <!-- <img
                  @click.stop="onSelectThirdMajor(secondItem, _item)"
                  :src="_item.checked ? check : uncheck"
                  class="selected-img"
                  alt=""
                /> -->
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { throttle } from 'lodash-es';
import check from '@/assets/images/selected.png';
import uncheck from '@/assets/images/unselected.png';
import arrowDown from '@/assets/images/arrowDown.png';

const props = defineProps({
  majorList: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['select']);

// 当前正在看的二级专业
const scrollCurrentSecondCategory = ref({});
// 添加标记变量，用于控制滚动状态
const isManualScrolling = ref(false);
// 添加防抖时间常量
const SCROLL_DEBOUNCE_TIME = 500;
// 添加滚动动画标记
const isScrolling = ref(false);
// 添加目标索引记录
const targetCategoryIndex = ref(-1);
// 左侧当前选中索引
const firstCategoryIndex = ref(0);
// 右侧容器引用
const rightContainer = ref(null);
// 当前选中三级专业
const currentSelectMajorList = ref([]);

// 选中当前二级
const onSelectSecondeMajor = (currentItem) => {
  currentItem.checked = !currentItem.checked;
  currentItem.children.forEach((_item) => {
    _item.checked = currentItem.checked;
  });
};

// 选中当前三级
const onSelectThirdMajor = (fatherItem, currentItem) => {
  currentItem.checked = !currentItem.checked;
  const selectedItem = fatherItem.children.filter((_item) => _item.checked);
  if (selectedItem.length == fatherItem.children.length) {
    fatherItem.checked = true;
  } else {
    fatherItem.checked = false;
  }
};

// 清除已选类型
const clear = () => {
  currentSelectMajorList.value = [];
  props.majorList.forEach((item) => {
    item.children.forEach((_item) => {
      _item.checked = false;
      if (_item.children) {
        _item.children.forEach((child) => {
          child.checked = false;
        });
      }
    });
  });
};

// 确定已选类型
const confirm = () => {
  emit('select', currentSelectMajorList.value);
};

// 监听majorList, 并获取当前选中三级专业
watch(
  () => props.majorList,
  (newVal) => {
    const selectedMajors = [];
    // 遍历一级分类
    newVal.forEach((firstItem) => {
      // 遍历二级分类
      firstItem.children?.forEach((secondItem) => {
        // 遍历三级分类，找出所有checked为true的专业
        secondItem.children?.forEach((thirdItem) => {
          if (thirdItem.checked) {
            selectedMajors.push(thirdItem);
          }
        });
      });
    });
    currentSelectMajorList.value = selectedMajors;
    confirm();
  },
  { deep: true }
);

// 更新二级分类显示的函数
const updateSecondCategory = (item) => {
  // 如果是手动滚动过程中，不更新状态
  if (isManualScrolling.value || isScrolling.value) return;

  if (item && item !== scrollCurrentSecondCategory.value) {
    scrollCurrentSecondCategory.value = item;
  }
};

// 重置分类状态的函数
const resetCategoryState = () => {
  // 如果是手动滚动过程中，不重置状态
  if (isManualScrolling.value || isScrolling.value) return;

  scrollCurrentSecondCategory.value = {};
  if (!isManualScrolling.value) {
    firstCategoryIndex.value = 0;
    document
      .querySelector('.left-column')
      ?.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

// 获取三级专业或者显示隐藏三级专业
const onToggleSecondIndustry = async (currentItem) => {
  currentItem.showChildren = !currentItem.showChildren;
};

// 使用节流优化滚动处理函数
const handleIndustryScroll = throttle((e) => {
  const container = e.target;

  // 如果是手动滚动过程中，只检查是否到达目标位置
  if (isManualScrolling.value || isScrolling.value) {
    if (targetCategoryIndex.value !== -1) {
      const target =
        container.querySelectorAll('.category')[targetCategoryIndex.value];
      if (target) {
        const rect = target.getBoundingClientRect();
        const containerRect = container.getBoundingClientRect();
        // 当滚动到目标位置附近时，更新状态并重置标记
        if (Math.abs(rect.top - containerRect.top) <= 50) {
          firstCategoryIndex.value = targetCategoryIndex.value;
          scrollCurrentSecondCategory.value = {};
          isManualScrolling.value = false;
          isScrolling.value = false;
          targetCategoryIndex.value = -1;
        }
      }
    }
    return;
  }

  // 当滚动到顶部时，重置状态
  if (container.scrollTop === 0) {
    resetCategoryState();
    return;
  }

  // 处理一级分类的更新
  const firstTitles = container.querySelectorAll('.first-title');
  firstTitles.forEach((title, index) => {
    const rect = title.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();

    // 当first-title到达顶部时更新状态
    if (
      rect.top - containerRect.top <= 0 &&
      rect.bottom - containerRect.top > 0
    ) {
      firstCategoryIndex.value = index;
      // 更新左侧菜单滚动位置
      const leftColumn = document.querySelector('.left-column');
      const selectedItem =
        leftColumn?.querySelectorAll('.first-category')[index];
      if (leftColumn && selectedItem) {
        const targetScrollTop =
          selectedItem.offsetTop -
          leftColumn.clientHeight / 2 +
          selectedItem.clientHeight / 2;
        leftColumn.scrollTo({ top: targetScrollTop, behavior: 'smooth' });
      }

      // 更新当前选中的二级分类
      const currentFirstItem = props.majorList[index];
      if (
        currentFirstItem &&
        currentFirstItem.children &&
        currentFirstItem.children.length > 0
      ) {
        // 找到当前可见的第一个二级分类
        const secondItems = container.querySelectorAll('.second-item');
        for (let i = 0; i < secondItems.length; i++) {
          const secondRect = secondItems[i].getBoundingClientRect();
          if (secondRect.top - containerRect.top > 0) {
            const secondItemName = secondItems[i]
              .querySelector('.second-item-title span')
              .textContent.split('(')[0];
            const currentSecondItem = currentFirstItem.children.find(
              (item) => item.name === secondItemName
            );
            if (currentSecondItem) {
              updateSecondCategory(currentSecondItem);
              break;
            }
          }
        }
      }
    }
  });
}, 100);

const changeFirstCategory = async (index) => {
  // 设置滚动状态标记
  isManualScrolling.value = true;
  isScrolling.value = true;
  targetCategoryIndex.value = index;

  // 重置二级分类显示
  scrollCurrentSecondCategory.value = {};
  firstCategoryIndex.value = index;

  const target = rightContainer.value.querySelectorAll('.category')[index];
  if (!target) return;

  const containerTop = rightContainer.value.getBoundingClientRect().top;
  const targetTop = target.getBoundingClientRect().top;
  // 修改滚动位置计算，使目标位置距离顶部80px
  const scrollPosition =
    targetTop - containerTop + rightContainer.value.scrollTop;

  // 执行滚动
  rightContainer.value.scrollTo({
    top: scrollPosition,
    behavior: 'smooth'
  });

  // 设置一个较长的超时时间，确保滚动完全停止
  setTimeout(() => {
    if (isManualScrolling.value || isScrolling.value) {
      isManualScrolling.value = false;
      isScrolling.value = false;
      targetCategoryIndex.value = -1;
    }
  }, SCROLL_DEBOUNCE_TIME + 200);
};
</script>

<style scoped lang="scss">
.popover-wrap :deep(.van-popover__content) {
  .van-popover__action {
    width: 120px;
    color: #222;
    font-size: 18px;
  }
}
.professional-category {
  display: flex;
  flex-direction: row;
  height: 100%;
  width: 100%;
  position: relative;
  .left-column {
    flex: 1.2;
    background: #f4f6f8;
    height: 100%;
    box-sizing: border-box;
    overflow: scroll;
    // border-top-right-radius: 10px; /* 右上角圆角 */
    .first-category {
      padding: 14px 6px 14px 24px;
      text-align: left;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24px;
      color: #666666;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .first-category-active {
      @extend .first-category;
      background: #fff;
      color: $primary-color;
    }
  }
  .right-column {
    flex: 4;
    height: 100%;
    box-sizing: border-box;
    overflow: scroll;
    background: #f5f6f8;
    position: relative;
    padding-bottom: 90px;
    .category {
      margin-bottom: 6px;
      background: #fff;
      &:last-child {
        margin-bottom: 0;
      }
      .first-title {
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 14px 0 14px 52px;
        position: sticky;
        top: -1px;
        left: 0;
        width: 100%;
        font-weight: bold;
        font-size: 26px;
        color: #222;
        background: #ffffff;
        z-index: 1;
        box-sizing: border-box;
      }
      .second-item {
        justify-content: space-between;
        font-family: PingFang-SC, PingFang-SC;
        font-size: 26px;
        color: #666;
        border-top: 1px solid #f5f5f5;
        .second-item-title {
          display: flex;
          align-items: center;
          padding: 14px 18px 14px 82px;
          .arrow-icon {
            width: 12px;
            height: 12px;
            transition: transform 0.3s linear;
          }
          .arrow-rotate {
            transform: rotate(180deg);
          }
          .second-item-title-text {
            display: flex;
            align-items: center;
            margin-right: 10px;
            margin-left: 8px;
            min-width: 0;
            .text-content {
              flex: 1;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
              min-width: 0;
            }
            .count-text {
              flex-shrink: 0;
              white-space: nowrap;
            }
          }
          .selected-img {
            margin-left: auto;
            width: 28px;
            height: 28px;
          }
        }
        .float-title {
          position: sticky;
          top: 24px;
          left: 0;
          background: #fff;
          color: $primary-color;
          box-shadow: 0px 1px 4px 0px rgba(228, 226, 226, 0.5);
        }
        .third-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 14px 17px 14px 122px;
          color: #6d787f;
          background: #e9f9ff;
          transition: all 0.3s ease;
          &:not(:last-child) {
            border-bottom: 1px solid #eaebec;
          }
          .selected-img {
            width: 28px;
            height: 28px;
          }
        }
        .third-item-special {
          font-weight: bold;
          padding: 8px 0 8px 30px;
          color: $primary-color;
          background: #fffaf3;
          transition: all 0.3s ease;
          border-bottom: 1px solid #dee9f0;
        }
      }
    }
  }
}
</style>
